package mh.lightremote;

import java.io.IOException;
import java.io.OutputStream;
import java.text.DecimalFormat;
import java.util.Observable;
import java.util.Observer;

import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.EditText;
import android.widget.SeekBar;

public class MainActivity extends Activity implements Observer {
	BTController.DefaultBTServiceConnection serviceConnection = new BTController.DefaultBTServiceConnection( this );
	
	private LightModel lightModel;
	
	private SeekBar seekRed;
	private SeekBar seekGreen;
	private SeekBar seekBlue;
	
	private EditText editRed;
	private EditText editGreen;
	private EditText editBlue;
	
    @Override
    public void onCreate(Bundle savedInstanceState)  {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        lightModel = new LightModel( 0, 0, 0 );
        lightModel.addObserver( this );
        
        seekRed = (SeekBar) findViewById(R.id.seekRed);
        editRed = (EditText) findViewById( R.id.editRed );
        seekRed.setOnSeekBarChangeListener( new SeekBar.OnSeekBarChangeListener() {
			public void onStopTrackingTouch(SeekBar seekBar) {}
			public void onStartTrackingTouch(SeekBar seekBar) {}
			
			public void onProgressChanged(SeekBar seekBar, int progress,
					boolean fromUser) {
				lightModel.setRed( progress );
			}
		});
        
        
        seekGreen = (SeekBar) findViewById(R.id.seekGreen);
        editGreen = (EditText) findViewById( R.id.editGreen );
        seekGreen.setOnSeekBarChangeListener( new SeekBar.OnSeekBarChangeListener() {
			public void onStopTrackingTouch(SeekBar seekBar) {}
			public void onStartTrackingTouch(SeekBar seekBar) {}
			
			public void onProgressChanged(SeekBar seekBar, int progress,
					boolean fromUser) {
				lightModel.setGreen( progress );
			}
		});
        
        seekBlue = (SeekBar) findViewById(R.id.seekBlue);
        seekBlue.setOnSeekBarChangeListener( new SeekBar.OnSeekBarChangeListener() {
			public void onStopTrackingTouch(SeekBar seekBar) {}
			public void onStartTrackingTouch(SeekBar seekBar) {}
			
			public void onProgressChanged(SeekBar seekBar, int progress,
					boolean fromUser) {
				lightModel.setBlue( progress );
			}
		});
        
        editBlue = (EditText) findViewById( R.id.editBlue );
        editBlue.addTextChangedListener( new TextWatcher() {
			private String oldValue;
        	
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				// TODO Auto-generated method stub
				
			}
			
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				oldValue = s.toString();
			}
			
			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub
				int currentValue = 0;
				try {
					currentValue = Integer.parseInt( s.toString() );
				} catch( NumberFormatException e )  {
					
				}
				
				if( lightModel.getBlue() != currentValue ) {
					lightModel.setBlue( currentValue );
				}
			}
		});
        
        startService( new Intent( this, BTController.class ) );
    }
    
    @Override
    protected void onStart() {
        bindService(new Intent(this, BTController.class), serviceConnection, Context.BIND_AUTO_CREATE);

    	super.onStart();
    }
    
    @Override
    protected void onStop() {
    	unbindService( serviceConnection );
    	
    	super.onStop();
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }
    
    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
    	MenuItem icon = (MenuItem) menu.findItem(R.id.menReconnect);
    	icon.setOnMenuItemClickListener( new MenuItem.OnMenuItemClickListener() {
			
			@Override
			public boolean onMenuItemClick(MenuItem item) {
				serviceConnection.getBTController().close();
				try {
					Thread.currentThread().sleep( 1000 );
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				serviceConnection.getBTController().setupConnection( MainActivity.this );
				
				return true;
			}
		});
    	
    	return super.onPrepareOptionsMenu(menu);
    }
    
	public void update(Observable arg0, Object arg1) {
		editRed.setText( String.valueOf( lightModel.getRed() ) );
		editGreen.setText( String.valueOf( lightModel.getGreen() ) );
		editBlue.setText( String.valueOf( lightModel.getBlue() ) );
		
		seekRed.setProgress( lightModel.getRed() );
		seekGreen.setProgress( lightModel.getGreen() );
		seekBlue.setProgress( lightModel.getBlue() );
		
		BTController bTController = serviceConnection.getBTController();
		
		if( bTController != null ) {
			OutputStream outputStream = bTController.getOutputStream();
			DecimalFormat decimalFormat = new DecimalFormat  ( "000" );
			String command = 	"cmd" + 
								decimalFormat.format( lightModel.getRed() ) +
								decimalFormat.format( lightModel.getGreen() ) +
								decimalFormat.format( lightModel.getBlue() ) +
								"\n";
			
			try {
				outputStream.write( command.getBytes( "ASCII" ) );
				outputStream.flush();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    	if( requestCode == BTController.REQUEST_ENABLE_BT ) {
    		if( resultCode == RESULT_OK ) {
    			serviceConnection.getBTController().setupConnection( this );
    		} else if( resultCode == RESULT_CANCELED ) {
    			finish();
    		}
    	}
    	
    	super.onActivityResult(requestCode, resultCode, data);
    }
}
